package org.ysh.service;

import org.springframework.stereotype.Service;
import org.ysh.domain.UserRole;
import org.ysh.mapper.UserRoleMapper;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserRoleService extends BaseService<Integer, UserRole>{
    public UserRoleService(UserRoleMapper baseMapper) {
        super(baseMapper);
    }

    public void deleteUserRoleByRole(int roleId){
        ((UserRoleMapper)baseMapper).deleteUserRoleByRole(roleId);
    }

    public void deleteUserRoleByUser(int userId){
        ((UserRoleMapper)baseMapper).deleteUserRoleByUser(userId);
    }

    /**
     * 批量插入
     * @param userRoles
     */
    public void batchInsert(List<UserRole> userRoles){
        if(userRoles == null || userRoles.isEmpty()) {
            return;
        }
        for (UserRole userRole : userRoles) {
            baseMapper.insert(userRole);
        }
    }

    public List<UserRole> findUsersByRoleId(int roleId){
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleId);
        return findByPage(userRole);
    }

    public void saveRoleUsers(Integer roleId,Integer[] userIds){
        //先清除原来的角色用户配置信息
        deleteUserRoleByRole(roleId);
        Arrays.stream(userIds).forEach(userId->{
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRole.setCreateTime(new Date());
            baseMapper.insert(userRole);
        });
    }

}
